package ${domain}.action.ajax.wsys;

import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import ${domain}.frame.auth.LocalData;
import ${domain}.frame.auth.Token;
import ${domain}.frame.base.BaseResponse;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.excel.WExcel;
import ${domain}.frame.excel.exception.TemplateNotMatchException;
import ${domain}.frame.utils.CookieUtil;
import ${domain}.frame.utils.LogUtil;
import ${domain}.frame.utils.MapperUtil;
import ${domain}.frame.utils.ResponseUtil;
import ${domain}.frame.utils.ValidationUtil;
import ${domain}.module.wsys.ent.User;
import ${domain}.module.wsys.mgr.TokensManager;
import ${domain}.module.wsys.mgr.UserManager;
import ${domain}.module.wsys.req.TokensLogoutRequest;
import ${domain}.module.wsys.req.UserChangePwdRequest;
import ${domain}.module.wsys.req.UserCreateRequest;
import ${domain}.module.wsys.req.UserDeleteRequest;
import ${domain}.module.wsys.req.UserFindRequest;
import ${domain}.module.wsys.req.UserLoginRequest;
import ${domain}.module.wsys.req.UserLogoutRequest;
import ${domain}.module.wsys.req.UserResetPwdRequest;
import ${domain}.module.wsys.req.UserUpdateRequest;
import ${domain}.module.wsys.rsp.TokensLogoutResponse;
import ${domain}.module.wsys.rsp.UserChangePwdResponse;
import ${domain}.module.wsys.rsp.UserCreateResponse;
import ${domain}.module.wsys.rsp.UserDeleteResponse;
import ${domain}.module.wsys.rsp.UserFindResponse;
import ${domain}.module.wsys.rsp.UserLoginResponse;
import ${domain}.module.wsys.rsp.UserLogoutResponse;
import ${domain}.module.wsys.rsp.UserResetPwdResponse;
import ${domain}.module.wsys.rsp.UserUpdateResponse;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class UserAjax {

    @Autowired
    private TokensManager tokensManager;
    @Autowired
    private UserManager userManager;

    public UserCreateResponse create(UserCreateRequest request) {
        return userManager.create(request, LocalData.getToken());
    }

    public UserDeleteResponse delete(UserDeleteRequest request) {
        return userManager.delete(request, LocalData.getToken());
    }

    public UserUpdateResponse update(UserUpdateRequest request) {
        return userManager.update(request, LocalData.getToken());
    }

    public UserChangePwdResponse changePwd(UserChangePwdRequest request) {
        String admin = LocalData.getEnvironment().getProperty("web.url.auth.admin", "admin");
        if (admin.equals(LocalData.getToken().getUserName())) {
            UserChangePwdResponse response = new UserChangePwdResponse();
            response.addError(ErrorType.BUSINESS_ERROR, "超级管理员无法通过网页变更登录密码!");
            return response;
        }
        return userManager.changePwd(request, LocalData.getToken());
    }

    public UserResetPwdResponse resetPwd(UserResetPwdRequest request) {
        return userManager.resetPwd(request, LocalData.getToken());
    }

    public UserFindResponse find(UserFindRequest request) {
        return userManager.find(request, LocalData.getToken());
    }

    public UserLoginResponse login(UserLoginRequest request, HttpServletResponse httpServletResponse) {
        UserLoginResponse response = userManager.login(request, LocalData.getToken());
        if (!response.hasError()) {
            Cookie cookie = CookieUtil.newCookie("token", response.getToken());
            httpServletResponse.addCookie(cookie);
        }
        return response;
    }

    public UserLogoutResponse logout(UserLogoutRequest request) {
        UserLogoutResponse response = new UserLogoutResponse();

        Token token = LocalData.getToken();
        if (token != null) {
            TokensLogoutRequest tokensLogoutRequest = new TokensLogoutRequest();
            tokensLogoutRequest.setToken(token.getToken());
            TokensLogoutResponse tokensLogoutResponse = tokensManager.logout(tokensLogoutRequest, LocalData.getSysToken());
            if (tokensLogoutResponse.hasError()) {
                response.addErrors(tokensLogoutResponse.getErrors());
                return response;
            }
        }
        CookieUtil.clearCookie("token");
        return response;
    }

    public Object template() {
        return ResponseUtil.apply(new WExcel<>(User.class));
    }

    public Object exports(UserFindRequest request) {
        UserFindResponse response = userManager.find(request, LocalData.getToken());
        if (response.hasError()) {
            return response;
        } else if (response.getTotalCount() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "导出数据为空");
            return response;
        }
        return ResponseUtil.apply(new WExcel<>(User.class).addDatas(response.getResult()));
    }

    public Object imports(MultipartFile file) {
        BaseResponse baseResponse = new BaseResponse();
        try {
            // 检查文件格式
            String originalFilename = file.getOriginalFilename() != null ? file.getOriginalFilename() : "";
            if (originalFilename.matches("\\.xlsx?")) {
                baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件格式错误！");
                return baseResponse;
            }
            // 兼容2003以前老版本.xls
            ExcelTypeEnum excelTypeEnum = file.getOriginalFilename().endsWith(".xlsx") ? ExcelTypeEnum.XLSX : ExcelTypeEnum.XLS;
            WExcel sheet = new WExcel<>(User.class).read(file.getBytes(), excelTypeEnum, new WExcel.Processor<User>() {
                @Override
                public List<String> exec(User o, int index) {
                    UserCreateRequest request = MapperUtil.map(o, UserCreateRequest.class);
                    return ValidationUtil.validate(request);
                }
            });

            if (sheet.hasError()) {
                return ResponseUtil.apply(sheet.getBytes(), sheet.getName() + "-检查.xlsx");
            } else {
                return baseResponse;
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.dumpException(e);
            baseResponse.addError(ErrorType.BUSINESS_ERROR, "上传文件出错");
        } catch (TemplateNotMatchException e) {
            baseResponse.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
        }
        return baseResponse;
    }
}
